//
//  WishCloudViewController.m
//  eGifr
//
//  Created by Phien Tram on 8/4/13.
//  Copyright (c) 2013 eGiftr. All rights reserved.
//

#import "WishCloudViewController.h"
#import "TermLabel.h"
#import "Utils.h"
#import "UserDefaultHelper.h"
#import "AppDelegate.h"
#import "ServiceNameMapper.h"
#import "FindKeyword.h"
#import "Global.h"

#define FLYING_LABEL_MIN_FONT_SIZE  14
#define FLYING_LABEL_MAX_FONT_SIZE  17

@interface WishCloudViewController ()
{
    CGRect wishCloudFrame;
}
@property (nonatomic, retain) NSTimer *updateTimer;
@end

@implementation WishCloudViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //set frame to center
    self.wishesAppearLikeThisLabel.hidden = YES;
    self.flickupGuideLabel.hidden = YES;
    self.flickupArrowImageView.hidden = YES;
    self.flickdownGuideLabel.hidden = YES;
    self.flickdownArrowImageView.hidden = YES;
    
    [self setCenterFrameForView:self.welcomeLabel];
    [self setCenterFrameForView:self.wishesAppearLikeThisLabel];
    [self setCenterFrameForView:self.flickupGuideLabel];
    CGRect frame = self.flickupArrowImageView.frame;
    frame.origin.y = self.flickupGuideLabel.frame.origin.y - frame.size.height;
    self.flickupArrowImageView.frame = frame;
    
    [self setCenterFrameForView:self.flickdownGuideLabel];
    frame = self.flickdownArrowImageView.frame;
    frame.origin.y = self.flickdownGuideLabel.frame.origin.y + self.flickdownGuideLabel.frame.size.height;
    self.flickdownArrowImageView.frame = frame;
    
    if ([Global sharedGlobal].allKeywords.count == 0) {
        [Global sharedGlobal].allKeywords = [Utils getAllKeywords];
    }
    
    //identify the wish cloud frame
    wishCloudFrame = CGRectMake(0, 0, SCREEN_WIDTH, 160);
    
    
    if (self.myWishCloudLabels == nil) {
        self.myWishCloudLabels = [NSMutableArray array];
    }
    self.removedLabels = [NSMutableArray array];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([UserDefaultHelper getAppToken].length > 0) {
        [SharedAppDelegate startSpinner:@"Loading..."];
//        self.dataManager = [DataManager findKeywords:self query:@"" cate:@"" appToken:[UserDefaultHelper getAppToken]];
        self.dataManager = [DataManager getRecommendedKeywords:self appToken:[UserDefaultHelper getAppToken]];
    } else {
        self.scrollingTerms = [NSMutableArray arrayWithObjects:
                               @"Bowling",
                               @"Carnival",
                               @"Exhibit",
                               @"Flying",
                               @"Golf",
                               @"Improv comedy",
                               @"Marathon",
                               @"Massage",
                               @"Orchestra",
                               @"Racing",
                               @"RF Racing",
                               @"Sports Tickets",
                               @"Symphony",
                               @"Wine Tasting",
                               nil];
        [self createTermLabelsForFlying];
    }
    
    if (self.myWishList.count == 0) {
        if ([UserDefaultHelper getShowWelcomeTips]) {
            [UserDefaultHelper setShowWelcomeTips:NO];
            //Step 1
            [self animateWelcomeText];
        } else {
            self.welcomeLabel.hidden = YES;
            
            if ([_updateTimer isValid]) {
                [_updateTimer invalidate];
            }
            self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f target:self selector:@selector(update) userInfo:nil repeats:YES];
        }
    } else {
        self.welcomeLabel.hidden = YES;
        
        
//        [SharedAppDelegate startSpinner:@"Loading..."];
//        self.dataManager = [DataManager getWishListByUserId:self userId:[UserDefaultHelper getUserId] appToken:[UserDefaultHelper getAppToken] page:[NSNumber numberWithInt:1]];
        
        
    }
}

#pragma mark - IBAction methods

- (IBAction)tipsButtonOnClicked:(id)sender
{
    
}

- (IBAction)doneButtonOnClicked:(id)sender
{
    if (_myWishCloudLabels.count >= MIN_WISHCLOUD_TERMS_AMOUNT) {
        //save my wishlist
        NSMutableArray *mutableArray = [NSMutableArray array];
        NSMutableArray *mutableArray2 = [NSMutableArray array];
        for (UILabel *label in _myWishCloudLabels) {
            FindKeyword *found = [self findKeywordObject:label.text];
            if (found) {
                [mutableArray2 addObject:found];
            }
            [mutableArray addObject:label.text];
        }
        AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        appDelegate.myWishList = mutableArray;
        [UserDefaultHelper setMyWishList:mutableArray];
        
//        [_delegate wishCloudViewDone:self];
        if ([UserDefaultHelper getAppToken].length > 0) {
            [SharedAppDelegate startSpinner:@"Loading..."];
            self.dataManager = [DataManager saveWishesByUserId:self userId:[UserDefaultHelper getUserId] keywords:[NSArray arrayWithArray:mutableArray2] appToken:[UserDefaultHelper getAppToken]];
        } else {
            //done immediately then save wish list later
            [_delegate wishCloudViewDone:self];
        }
        
    }
}

#pragma mark - Private methods

- (void)createTermLabelsForFlying
{
    //identify the flying frame
    CGRect flyingFrame = CGRectMake(0, 165, SCREEN_WIDTH, 200);
    CGFloat bottomHeight = 60;
    CGFloat flyingHeight = self.view.frame.size.height - bottomHeight - flyingFrame.origin.y;
    flyingHeight -= 10; //for bottom padding.
    flyingFrame.size.height = flyingHeight;
    NSLog(@"FRAME:%@ flyHeight:%.2f", NSStringFromCGRect(self.view.frame), flyingHeight);
    
    CGFloat nextYOffset = flyingFrame.origin.y;
    CGFloat nextXOffset = SCREEN_WIDTH;
    self.scrollingLabels = [NSMutableArray array];
    for (NSUInteger i = 0; i < self.scrollingTerms.count;i++) {
        NSString *text = self.scrollingTerms[i];
        int randomOffset = [Utils randomValue:0 upperBound:SCREEN_WIDTH];
        TermLabel *label = [[TermLabel alloc] initWithFrame:CGRectMake(nextXOffset + randomOffset, nextYOffset, SCREEN_WIDTH, SCROLLING_LABEL_HEIGHT)];
        label.tag = i + SCROLLING_LABEL_BASE_TAG;
        label.text = text;
        label.font = [UIFont systemFontOfSize:[Utils randomValue:FLYING_LABEL_MIN_FONT_SIZE upperBound:FLYING_LABEL_MAX_FONT_SIZE]];
        CGSize constraint = CGSizeMake(SCREEN_WIDTH, SCROLLING_LABEL_HEIGHT);
        CGSize size = [text sizeWithFont:label.font constrainedToSize:constraint];
        size.width += 2 * MY_WISHCLOUD_LABEL_HORIZONTAL_PADDING;
        CGRect frame = label.frame;
        frame.size = size;
        
        label.frame = frame;
        label.originalFrame = label.frame; //remember original point for future uses
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = UITextAlignmentCenter;
        label.userInteractionEnabled = YES;
        [self.view addSubview:label];
        
        [self.scrollingLabels addObject:label];
        
        nextYOffset += size.height;
        if (nextYOffset > (flyingFrame.origin.y + flyingHeight)) {
            break;
            nextYOffset = flyingFrame.origin.y;
            nextXOffset += SCREEN_WIDTH;
        }
    }
}

- (FindKeyword *)findKeywordObject:(NSString *)text
{
    NSArray *allKeywords = [Global sharedGlobal].allKeywords;
    FindKeyword *result = nil;
    for (FindKeyword *keyword in allKeywords) {
        if ([keyword.keyword isEqualToString:text]) {
            result = keyword;
            break;
        }
    }
    
    return result;
}

- (void)generateMyWishCloudLabels:(NSArray *)myWishList
{
    self.myWishCloudLabels = [NSMutableArray array];
    for (UILabel *label in self.scrollingLabels) {
        BOOL found = NO;
        for (NSString *wishTerm in myWishList) {
            if ([label.text isEqualToString:wishTerm]) {
                found = YES;
                break;
            }
        }
        if (found) {
            [self.myWishCloudLabels addObject:label];
        }
    }
    
    //determine the target frame
    NSInteger index = 1;
    for (NSInteger k = _myWishCloudLabels.count - 1; k >= 0; k--) {
        TermLabel *label = _myWishCloudLabels[k];
        label.backgroundColor = [UIColor whiteColor];
        label.textColor = [UIColor redColor];
        label.layer.borderColor = [UIColor lightGrayColor].CGColor;
        label.layer.borderWidth = 1.0f;
        label.layer.cornerRadius = 4.0f;
        
        //animate to move up to the wish cloud above
        CGPoint origin;
        origin.x = MY_WISHCLOUD_LABEL_ORIGIN_X;
        origin.y = CGRectGetMaxY(wishCloudFrame) - index * (MY_WISHCLOUD_LABEL_HEIGHT + MY_WISHCLOUD_LABEL_SEPARATOR_HEIGHT);
        CGRect frame = label.frame;
        frame.origin = origin;
        frame.size.height = MY_WISHCLOUD_LABEL_HEIGHT;
        label.frame = frame;
        label.frame = frame;
        
        [label removeAllGestureRecognizers];
        //swipe gesture to handle delete added item
        UISwipeGestureRecognizer *gestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
        gestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
        [label addGestureRecognizer:gestureRecognizer];
        
        index++;
    }
    
    
    if ([_updateTimer isValid]) {
        [_updateTimer invalidate];
    }
    self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f target:self selector:@selector(update) userInfo:nil repeats:YES];
}

- (void)update
{
    for (NSUInteger i = 0; i < self.scrollingLabels.count;i++) {
        TermLabel *label = self.scrollingLabels[i];
        if (![_myWishCloudLabels containsObject:label] && ![_removedLabels containsObject:label])
        {
            if (label.state == TERM_TOUCH_EVENT_STATE_RESUMED) {
                CGRect frame = label.frame;
                frame.origin.x -= 1;
                if (frame.origin.x < -frame.size.width) {
                    frame.origin.x = label.originalFrame.origin.x;
                }
                label.frame = frame;
            } else if (label.state == TERM_TOUCH_EVENT_STATE_FLICK_UP) {
                //highlight the selected label
                label.backgroundColor = [UIColor whiteColor];
                label.textColor = [UIColor redColor];
                label.layer.borderColor = [UIColor lightGrayColor].CGColor;
                label.layer.borderWidth = 1.0f;
                label.layer.cornerRadius = 4.0f;
                CGRect frame = label.frame;
                frame.size.height = MY_WISHCLOUD_LABEL_HEIGHT;
                label.frame = frame;
            } else if (label.state == TERM_TOUCH_EVENT_STATE_FINISH_FLICK_UP) {
                label.backgroundColor = [UIColor whiteColor];
                label.textColor = [UIColor redColor];
                label.layer.borderColor = [UIColor lightGrayColor].CGColor;
                label.layer.borderWidth = 1.0f;
                label.layer.cornerRadius = 4.0f;
                CGRect frame = label.frame;
                frame.size.height = MY_WISHCLOUD_LABEL_HEIGHT;
                label.frame = frame;
                [self.myWishCloudLabels addObject:label];
                if (self.myWishCloudLabels.count >= MIN_WISHCLOUD_TERMS_AMOUNT) {
                    self.wishCloudButton.enabled = YES;
                }
                
                //determine the target frame
                NSInteger index = 1;
                for (NSInteger k = _myWishCloudLabels.count - 1; k >= 0; k--) {
                    UILabel *wishLabel = _myWishCloudLabels[k];
                    
                    //animate to move up to the wish cloud above
                    CGPoint origin;
                    origin.x = MY_WISHCLOUD_LABEL_ORIGIN_X;
                    origin.y = CGRectGetMaxY(wishCloudFrame) - index * (MY_WISHCLOUD_LABEL_HEIGHT + MY_WISHCLOUD_LABEL_SEPARATOR_HEIGHT);
                    frame = wishLabel.frame;
                    frame.origin = origin;
                    
                    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                        wishLabel.frame = frame;
                    } completion:^(BOOL finished) {
                        
                    }];
                    
                    index++;
                }
                
                [label removeAllGestureRecognizers];
                //swipe gesture to handle delete added item
                UISwipeGestureRecognizer *gestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
                gestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
                [label addGestureRecognizer:gestureRecognizer];
            } else if (label.state == TERM_TOUCH_EVENT_STATE_FLICK_DOWN) {
                //highlight the selected label
                label.backgroundColor = [UIColor whiteColor];
                label.layer.borderColor = [UIColor lightGrayColor].CGColor;
                label.layer.borderWidth = 1.0f;
                label.layer.cornerRadius = 4.0f;
                CGRect frame = label.frame;
                frame.size.height = MY_WISHCLOUD_LABEL_HEIGHT;
                label.frame = frame;
            } else if (label.state == TERM_TOUCH_EVENT_STATE_FINISH_FLICK_DOWN) {
                [self.removedLabels addObject:label];
                CGRect frame = label.frame;
                frame.origin.y = self.view.frame.size.height;
                frame.origin.x = (self.view.frame.size.width - frame.size.width) * 0.5f;
                [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                    label.frame = frame;
                } completion:^(BOOL finished) {
                    
                }];
            }
        }
        
    }
}

- (void)animateScrollingLabel:(UILabel *)label
{
    CGRect frame = label.frame;
    frame.origin.x = self.view.frame.size.width;
    self.wishesAppearLikeThisLabel.frame = frame;
    self.wishesAppearLikeThisLabel.hidden = NO;
    
    frame.origin.x = - frame.size.width;
    [UIView animateWithDuration:5.0 delay:1.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.wishesAppearLikeThisLabel.frame = frame;
    } completion:^(BOOL finished) {
        NSLog(@"WISHES MOVING COMPLETION");
        //animate to disappear the welcome text
        self.wishesAppearLikeThisLabel.hidden = YES;
        //Step 3
        [self animateFlickupGuideText];
    }];
}

- (void)setCenterFrameForView:(UIView *)view
{
    CGRect frame = view.frame;
    frame.origin.x = (self.view.frame.size.width - frame.size.width) * 0.5f;
    frame.origin.y = (self.view.frame.size.height - frame.size.height) * 0.5f;
    view.frame = frame;
}

- (void)animateWelcomeText
{
    CGRect frame = self.welcomeLabel.frame;
    frame.origin.x = self.view.frame.size.width;
    self.welcomeLabel.frame = frame;
    self.welcomeLabel.hidden = NO;
    
    frame.origin.x = (self.view.frame.size.width - frame.size.width) * 0.5f;
    [UIView animateWithDuration:0.75 delay:0.5 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.welcomeLabel.frame = frame;
    } completion:^(BOOL finished) {
        NSLog(@"WELCOME MOVING COMPLETION");
        //animate to disappear the welcome text
        
        [UIView animateWithDuration:0.75f delay:1.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{
            
        } completion:^(BOOL finished) {
            if (finished) {
                self.welcomeLabel.alpha = 1.0;
                [UIView animateWithDuration:0.75 animations:^{
                    self.welcomeLabel.alpha = 0;
                } completion:^(BOOL finished) {
                    self.welcomeLabel.hidden = YES;
                    //Step 2
                    [self animateWishAppearLikeThisText];
                }];
                
            }
        }];
    }];
}

- (void)animateWishAppearLikeThisText
{
    CGRect frame = self.wishesAppearLikeThisLabel.frame;
    frame.origin.x = self.view.frame.size.width;
    self.wishesAppearLikeThisLabel.frame = frame;
    self.wishesAppearLikeThisLabel.hidden = NO;
    
    frame.origin.x = - frame.size.width;
    [UIView animateWithDuration:5.0 delay:0.25 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.wishesAppearLikeThisLabel.frame = frame;
    } completion:^(BOOL finished) {
        NSLog(@"WISHES MOVING COMPLETION");
        //animate to disappear the welcome text
        self.wishesAppearLikeThisLabel.hidden = YES;
        //Step 3
        [self animateFlickupGuideText];
    }];
}

//=====================Drag or flick up on the ones you like=================//
- (void)animateFlickupGuideText
{
    CGRect frame = self.flickupGuideLabel.frame;
    frame.origin.x = self.view.frame.size.width;
    self.flickupGuideLabel.frame = frame;
    self.flickupGuideLabel.hidden = NO;
    
    frame.origin.x = (self.view.frame.size.width - frame.size.width) * 0.5f;
    [UIView animateWithDuration:0.75 delay:0.25 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.flickupGuideLabel.frame = frame;
    } completion:^(BOOL finished) {
        NSLog(@"FLICKUP GUIDE MOVING COMPLETION");
        //Step 4
        [self animateArrowFadeAway];
    }];
}

- (void)animateArrowFadeAway
{
    self.flickupArrowImageView.hidden = NO;
    self.flickupArrowImageView.alpha = 1.0f;
    // Then fades it away after 2 seconds (the cross-fade animation will take 0.5s)
    [UIView animateWithDuration:0.5 delay:1.0 options:0 animations:^{
        // Animate the alpha value of your imageView from 1.0 to 0.0 here
        self.flickupArrowImageView.alpha = 0.0f;
    } completion:^(BOOL finished) {
        // Once the animation is completed and the alpha has gone to 0.0, hide the view for good
        self.flickupArrowImageView.hidden = YES;
        //Step 5: Text resumes and scrolls off the left side of screen.
        [self animateScrollFlickupGuideOffToLeftScreen];
    }];
}

- (void)animateScrollFlickupGuideOffToLeftScreen
{
    CGRect frame = self.flickupGuideLabel.frame;
    frame.origin.x = - frame.size.width;
    [UIView animateWithDuration:0.75 delay:0.25 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.flickupGuideLabel.frame = frame;
    } completion:^(BOOL finished) {
        NSLog(@"FLICKUP GUIDE MOVING COMPLETION");
        self.flickupGuideLabel.hidden = YES;
        //Step 6:
        [self animateFlickdownGuideText];
    }];
}
//=====================Drag or flick up on the ones you like=================//

//=====================Drag or flick down on the ones you don't like=================//
- (void)animateFlickdownGuideText
{
    CGRect frame = self.flickdownGuideLabel.frame;
    frame.origin.x = self.view.frame.size.width;
    self.flickdownGuideLabel.frame = frame;
    self.flickdownGuideLabel.hidden = NO;
    
    frame.origin.x = (self.view.frame.size.width - frame.size.width) * 0.5f;
    [UIView animateWithDuration:0.75 delay:0.25 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.flickdownGuideLabel.frame = frame;
    } completion:^(BOOL finished) {
        NSLog(@"FLICKDOWN GUIDE MOVING COMPLETION");
        //Step 7
        [self animateArrowDownFadeAway];
    }];
}

- (void)animateArrowDownFadeAway
{
    self.flickdownArrowImageView.hidden = NO;
    self.flickdownArrowImageView.alpha = 1.0f;
    // Then fades it away after 2 seconds (the cross-fade animation will take 0.5s)
    [UIView animateWithDuration:0.5 delay:1.0 options:0 animations:^{
        // Animate the alpha value of your imageView from 1.0 to 0.0 here
        self.flickdownArrowImageView.alpha = 0.0f;
    } completion:^(BOOL finished) {
        // Once the animation is completed and the alpha has gone to 0.0, hide the view for good
        self.flickdownArrowImageView.hidden = YES;
        //Step 8: Text resumes and scrolls off the left side of screen.
        [self animateScrollFlickdownGuideOffToLeftScreen];
    }];
}

- (void)animateScrollFlickdownGuideOffToLeftScreen
{
    CGRect frame = self.flickdownGuideLabel.frame;
    frame.origin.x = - frame.size.width;
    [UIView animateWithDuration:0.75 delay:0.25 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.flickdownGuideLabel.frame = frame;
    } completion:^(BOOL finished) {
        NSLog(@"FLICKDOWN GUIDE MOVING COMPLETION");
        self.flickdownGuideLabel.hidden = YES;
        //Step 9:
        [self animateTryItAndFadeAway];
    }];
}
//=====================Drag or flick down on the ones you don't like=================//

- (void)animateTryItAndFadeAway
{
    [self setCenterFrameForView:self.welcomeLabel];
    self.welcomeLabel.text = @"Try it!";
    self.welcomeLabel.hidden = NO;
    
    self.welcomeLabel.alpha = 1.0f;
    // Then fades it away after 2 seconds (the cross-fade animation will take 0.5s)
    [UIView animateWithDuration:0.5 delay:1.0 options:0 animations:^{
        // Animate the alpha value of your imageView from 1.0 to 0.0 here
        self.welcomeLabel.alpha = 0.0f;
    } completion:^(BOOL finished) {
        // Once the animation is completed and the alpha has gone to 0.0, hide the view for good
        if (finished) {
            self.welcomeLabel.hidden = YES;
            self.welcomeLabel.alpha = 1.0f;
            
            if ([_updateTimer isValid]) {
                [_updateTimer invalidate];
            }
            self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f target:self selector:@selector(update) userInfo:nil repeats:YES];
        }
    }];
}

#pragma mark - Handle swipe gesture recognizer

- (void)handleSwipe:(UIGestureRecognizer *)gestureRecognizer
{
    if (((UISwipeGestureRecognizer *)gestureRecognizer).direction == UISwipeGestureRecognizerDirectionLeft) {
        //remove label
        TermLabel *label = (TermLabel *)gestureRecognizer.view;
        label.state = TERM_TOUCH_EVENT_STATE_SWIPE_LEFT;
        [_myWishCloudLabels removeObject:label];
        NSLog(@"Swipe left %@", label.text);
        
        CGRect frame;
        //determine the target frame
        NSInteger index = 1;
        for (NSInteger k = _myWishCloudLabels.count - 1; k >= 0; k--) {
            UILabel *wishLabel = _myWishCloudLabels[k];
            
            //animate to move up to the wish cloud above
            CGPoint origin;
            if ([wishLabel isEqual:label]) {
                origin.x = -label.frame.size.width;
            } else {
                origin.x = MY_WISHCLOUD_LABEL_ORIGIN_X;
            }
            origin.y = CGRectGetMaxY(wishCloudFrame) - index * (MY_WISHCLOUD_LABEL_HEIGHT + MY_WISHCLOUD_LABEL_SEPARATOR_HEIGHT);
            frame = wishLabel.frame;
            frame.origin = origin;
            
            [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                wishLabel.frame = frame;
            } completion:^(BOOL finished) {
                
            }];
            
            index++;
        }
        
        //animate to move the selected label to left side
        CGPoint origin = label.frame.origin;
        origin.x = -label.frame.size.width;
        frame = label.frame;
        frame.origin = origin;
        
        [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            label.frame = frame;
        } completion:^(BOOL finished) {
            //and recover to original starting point
            if (finished) {
                label.state = TERM_TOUCH_EVENT_STATE_RESUMED;
                label.frame = label.originalFrame;
                label.backgroundColor = [UIColor clearColor];
                label.textColor = [UIColor blackColor];
                label.layer.borderWidth = 0.0f;
                [label removeGestureRecognizer:gestureRecognizer];
                [label addTapAndPanGestureRecognizer];
            }
        }];
    }
}

#pragma mark - DataManager delegate

- (void)dataManagerFinishGetData:(DataManager *)dataManager response:(id)response error:(NSError *)error
{
    [SharedAppDelegate stopSpinner];
    if (error) {
        if ([dataManager.serviceName isEqualToString:[ServiceNameMapper saveWishesByUserId]]) {
            if ([error code] == 600) {
                [_delegate wishCloudViewDone:self];
            }
        } else {
            if ([error code] == 211 || [error code] == 210) {
                //Token expired || invalid token
//                [[NSNotificationCenter defaultCenter] postNotificationName:kShouldShowLoginNotificationName object:nil];
            }
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry" message:error.localizedDescription delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
            [alertView show];
        }
    } else {
        if ([dataManager.serviceName isEqualToString:[ServiceNameMapper getWishListByUserId]]) {
            self.myWishTerm = response;
            NSLog(@"%@", response);
        } else if ([dataManager.serviceName isEqualToString:[ServiceNameMapper saveWishesByUserId]]) {
            [_delegate wishCloudViewDone:self];
        } else if ([dataManager.serviceName isEqualToString:[ServiceNameMapper findKeywords]]) {
            [Global sharedGlobal].allKeywords = response;
        } else if ([dataManager.serviceName isEqualToString:[ServiceNameMapper getRecommendedKeywords]]) {
            [Global sharedGlobal].recommendedKeywords = response;
            if ([Global sharedGlobal].recommendedKeywords.count > 0) {
                NSMutableArray *mutableArray = [NSMutableArray array];
                for (FindKeyword *keyword in [Global sharedGlobal].recommendedKeywords) {
                    [mutableArray addObject:keyword.keyword];
                }
                if (_myWishList.count > 0) {
                    for (NSString *keyword in _myWishList) {
                        if (![mutableArray containsObject:keyword]) {
                            [mutableArray addObject:keyword];
                        }
                    }
                }
                self.scrollingTerms = mutableArray;
            } else {
                self.scrollingTerms = [NSMutableArray arrayWithObjects:
                                       @"Bowling",
                                       @"Carnival",
                                       @"Exhibit",
                                       @"Flying",
                                       @"Golf",
                                       @"Improv comedy",
                                       @"Marathon",
                                       @"Massage",
                                       @"Orchestra",
                                       @"Racing",
                                       @"RF Racing",
                                       @"Sports Tickets",
                                       @"Symphony",
                                       @"Wine Tasting",
                                       nil];
                
            }
            
            [self createTermLabelsForFlying];
            
            if (_myWishList.count > 0) {
                [self generateMyWishCloudLabels:self.myWishList];
            }
            
            if (self.myWishCloudLabels.count >= MIN_WISHCLOUD_TERMS_AMOUNT) {
                self.wishCloudButton.enabled = YES;
            }
        } else {
            
        }
    }
}

@end
